$(document).ready(function() {

	const login = localStorage.getItem('login');
	const token = localStorage.getItem('token');
	console.log(login);
	console.log(token);

	if (login) {
		showLoggedInElements();
	} else {
		showLoggedOutElements();
	}


	const $loginPopup = $('#loginPopup');
	const $registerPopup = $('#registerPopup');
	const $showLogin = $('span:contains("登录")');
	const $showRegister = $('span:contains("注册")');
	const $closeLogin = $('.close-popup[data-dismiss="login"]');
	const $closeRegister = $('.close-popup[data-dismiss="register"]');
	const $goRegister = $('.go-register');
	const $goLogin = $('.go-login');
	const loginUrl = config.login;
	const registerUrl = config.register;
	let username;
	let password;
	let confirmPassword;
	let phone;

	function showLoggedInElements() {
		$('.dlxx').show();
		$('span:contains("登录")').hide();
		$('span:contains("注册")').hide();
		$('#tcdl').text('退出');
	}

	function showLoggedOutElements() {
		$('.dlxx').hide();
		$('span:contains("登录")').show();
		$('span:contains("注册")').show();
		$('#tcdl').text('');
	}

	function showLoginPopup() {
		console.log("准备显示登录弹窗");
		$loginPopup.show();
		console.log("登录弹窗显示状态：", $loginPopup.is(':visible'));
		$('#login').click(function() {
			phone = $("#po").val();
			password = $("#pw").val();
			$.ajax({
				type: "POST",
				url: loginUrl,
				data: {
					method: "login",
					phone: phone,
					password: password
				},
				xhrFields: {
					withCredentials: true
				},
				crossDomain: true,
				headers: {

					'Authorization': 'Bearer ' + localStorage.getItem('token')
				},
				success: function(res) {
					console.log(res);
					console.log("登录成功，响应：", res.msg);
					if (res.msg == "登录成功") {
						$loginPopup.hide();
						showLoggedInElements();
						localStorage.setItem('login', JSON.stringify(res))
						if (res.token) {
							localStorage.setItem('token', res.token);
						}
					} else {
						alert("登录失败，请检查账号密码");
					}
				},
				error: function(xhr, status, error) {
					console.log("登录请求出错：", error);
					// 可在此处添加更详细的登录失败提示逻辑，比如根据不同错误状态显示不同提示等
				}
			});
		});
	}

	function showRegisterPopup() {
		console.log("准备显示注册弹窗");
		$registerPopup.show();
		console.log("注册弹窗显示状态：", $registerPopup.is(':visible'));
	}

	function hidePopups() {
		console.log("准备隐藏所有弹窗");
		$loginPopup.hide();
		$registerPopup.hide();
		console.log("登录弹窗隐藏状态：", $loginPopup.is(':hidden'));
		console.log("注册弹窗隐藏状态：", $registerPopup.is(':hidden'));
	}

	function validateRegisterData() {
		username = $("#reg_username").val();
		password = $("#reg_password").val();
		confirmPassword = $("#reg_confirm_password").val();
		phone = $("#reg_phone").val();

		if (username === "") {
			alert("用户名不能为空");
			return false;
		}
		if (password === "") {
			alert("密码不能为空");
			return false;
		}
		if (confirmPassword === "") {
			alert("确认Password不能为空");
			return false;
		}
		if (phone === "") {
			alert("手机号不能为空");
			return false;
		}
		if (password !== confirmPassword) {
			alert("密码和确认Password不一致");
			return false;
		}
		// 这里还可以添加更多复杂的校验逻辑，比如手机号格式校验等
		return true;
	}

	function register() {
		if (validateRegisterData()) {
			var dataToSend = {
				method: "register",
				sname: username,
				password: password,
				// confirm_password: confirmPassword,
				phone: phone
			};
			console.log(username + " " + phone + " " + password);
			$.ajax({
				type: "POST",
				url: registerUrl,
				data: dataToSend,
				xhrFields: {
					withCredentials: true
				},
				crossDomain: true,
				success: function(res) {
					console.log("注册成功，响应：", res.msg);
					if (res.msg == "注册成功") {

						if (res.token) {
							localStorage.setItem('token', res.token);

						}
						$registerPopup.hide();
						showLoginPopup();
					} else {
						alert("注册失败，请检查输入信息");
					}
				},
				error: function(xhr, status, error) {
					console.log("注册请求出错：", error);
					// 可在此处添加更详细的注册失败提示逻辑
				}
			});
		}
	}

	// 点击显示登录弹窗
	$showLogin.click(showLoginPopup);

	// 点击显示注册弹窗
	$showRegister.click(showRegisterPopup);

	// 点击关闭登录弹窗
	$closeLogin.click(hidePopups);

	// 点击关闭注册弹窗
	$closeRegister.click(hidePopups);

	// 从登录弹窗跳转到注册弹窗
	$goRegister.click(function() {
		console.log("从登录弹窗跳转到注册弹窗");
		hidePopups();
		showRegisterPopup();
	});

	// 从注册弹窗跳转到登录弹窗
	$goLogin.click(function() {
		console.log("从注册弹窗跳转到登录弹窗");
		hidePopups();
		showLoginPopup();
	});

	// 为注册按钮添加点击事件
	$('#register').click(register);

	// 添加退出登录功能，点击#tcdl元素时执行退出登录操作，同时清除localStorage中的token
	$('#tcdl').click(function () {
	    localStorage.removeItem('token');
	    localStorage.removeItem('login');
	    showLoggedOutElements();
	});
});